import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
import { StorageService } from './storage.js'

axios.defaults.baseURL = process.env.VUE_APP_API_PATH;
axios.defaults.headers.post['Content-Type'] = 'application/json';

// If token exists set header
let token = StorageService.getToken();
if (token) {
    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}

export const ApiService = {
    init() {
        setupCache(axios, { interpretHeader: false });
    },
    removeHeader() {
        axios.defaults.headers.common = {}
    },
    get(apiPath, options = { cache: false }) {
        console.log("API Service - 请求路径:", apiPath);
        console.log("API Service - 请求选项:", options);
        
        // 创建一个新的选项对象，防止参数被覆盖
        const mergedOptions = {
            // 确保params存在且为对象
            params: options.params || {},
            // 保留缓存选项
            cache: options.cache || false
        };
        
        // 如果有其他选项，复制它们，但不覆盖已有的params
        if (options) {
            Object.keys(options).forEach(key => {
                if (key !== 'params') {
                    mergedOptions[key] = options[key];
                }
            });
        }
        
        console.log("API Service - 最终请求选项:", mergedOptions);
        return axios.get(apiPath, mergedOptions);
    },
    download(apiPath) {
        return axios({
            url: apiPath,
            method: 'GET',
            responseType: 'blob', // important
        })
    },
    post(apiPath, data) {
        return axios.post(apiPath, data);
    },

    put(apiPath, data) {
        return axios.put(apiPath, data)
    },

    delete(apiPath) {
        return axios.delete(apiPath)
    },
    axios() {
        return axios;
    },
}
